#!/usr/bin/python
# Filename: mysqldb.py

import logging
import MySQLdb

from mjs_public import singleton

from mjs_conf import mjs_conf
mjs_conf_mgr = mjs_conf.MjsConf()

class MjsMysqlDB(singleton.Singleton):
    client = None

    def __init__(self):
        try:
            # connect mysql

            # logging.info("db_user:%s db_passwd:%s db_name:%s" % (mjs_conf_mgr.db_user, mjs_conf_mgr.db_passwd, mjs_conf_mgr.db_name))

            self.client = MySQLdb.connect("localhost", mjs_conf_mgr.db_user, mjs_conf_mgr.db_passwd, mjs_conf_mgr.db_name)
            cursor = self.client.cursor()
            cursor.execute("SELECT VERSION()")
            version = cursor.fetchone()
            logging.info("connect mysql %s successed, mysql version : %s" % (mjs_conf_mgr.host, version[0]))
        except Exception, e:
            logging.error("connect mysql %s failed: %s" % (mjs_conf_mgr.host, e))

    def query(self, sql):
        if self.client == None:
            logging.error("database don't connect")
            return None

        # use cursor() function to fetch op cursor
        cursor = self.client.cursor()

        try:
            cursor.execute(sql)
            return cursor.fetchall()
        except Exception, e:
            logging.error("execut failed : %s, error : %s >>> " % (sql, str(e)))
            return None

    def execute(self, sql):
        if self.client == None:
            logging.error("database don't connect")
            return False

        cursor = self.client.cursor()

        try:
            cursor.execute(sql)
            self.client.commit()
            return True
        except Exception, e:
            logging.error("execute failed : %s, error : %s" % (sql, str(e)))
            self.client.rollback()
            return False

    def __del__(self):
        # close mysql conenct
        if self.client:
            self.client.close()
